﻿DECLARE @idMapping TABLE (rowNo INT, oldId INT NULL, newId INT NULL); 
DECLARE @rowCount INT
DECLARE @index INT 
DECLARE @currentId INT
DECLARE @newId INT

--Get existing rows for this user
INSERT INTO		 @idMapping
SELECT			 @@rowCount
				,ApplicationUserPaneId
				,NULL
FROM			 ApplicationUserPane
WHERE			 ApplicationUserPaneId = @templateId

--Set indexes
SET @rowCount = @@rowCount;
SET @index = 1;

--Loop through all result sets
WHILE (@index < @rowCount)
BEGIN
	SELECT @currentId = oldId FROM @idMapping WHERE rowNo = @index;
	
	--INSERT GROUP
	INSERT INTO ApplicationUserPaneGroup
	SELECT * FROM ApplicationUserPane
	WHERE  ApplicationUserPaneId = @currentId

	SET @newId = @@identity;

	--Get and update the temp table with the newly inserted id
	UPDATE	@idMapping
	SET		newId = @newId
	WHERE  ApplicationUserPaneId = @currentId

	--INSERT INTO GROUP INSTRUMENTS 
	INSERT INTO ApplicationUserGroupInstrument
	SELECT @newId, * FROM ApplicationUserPaneGroupInstrument
	WHERE ApplicationUserPaneGroupId = @currentId

	SET @index = @index + 1;
END
